package com.ynjt.client;


import com.ynjt.model.Message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.UUID;

public class ChatClient implements ActionListener {

    private String msgId;

    public static void main(String[] args) throws Exception {
        new ChatClient("localhost", 8080).initConn();
    }

    private final String host;
    private final int port;
    private final JTextArea inputText;
    private final JTextArea outputText;
    private Channel channel;

    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;

        JFrame frame = new JFrame();
        inputText = new JTextArea(10, 25);
        outputText = new JTextArea(15, 25);

        JButton button = new JButton("发送");
        button.addActionListener(this);

        JPanel panel = new JPanel();
        panel.add(inputText);
        panel.setBackground(Color.lightGray);

        frame.getContentPane().add(BorderLayout.NORTH, outputText);
        frame.getContentPane().add(BorderLayout.CENTER, panel);
        frame.getContentPane().add(BorderLayout.SOUTH, button);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        Date time = new Date();
        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initConn() {
        msgId = UUID.randomUUID().toString();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChatClientInitializer(this));
            channel = bootstrap.connect(host, port).sync().channel();

            final ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public void run() throws Exception {

        Message msg = new Message("1111",msgId,"3333",inputText.getText());

        if (inputText.getText().length() != 0) {
            channel.writeAndFlush(msg);
        }
        inputText.setText("");
    }

    public JTextArea getOutputText() {
        return outputText;
    }
}
